package com.pxmeta.app.task;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.dynamic.service.RedisLockService;
import com.pxmeta.order.dto.OrderEvaluateDTO;
import com.pxmeta.order.entity.UserOrderRecord;
import com.pxmeta.order.service.IOrderEvaluateService;
import com.pxmeta.order.service.IUserOrderRecordService;
import com.pxmeta.order.vo.OrderEvaluateVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class SkillTask {

    private final IUserOrderRecordService userOrderRecordService;
    private final RedisLockService redisLockService;


    /**
     * 订单自动完成
     * 每10分钟触发一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    @Transactional(rollbackFor = RuntimeException.class)
    public void orderAutomaticCompletion(){
        String sendCodeLockKey = "orderAutomaticCompletion";
        String lock = redisLockService.lock(sendCodeLockKey, 1000, 200);
        log.info("扫描系统自动完成的订单");
        if (StringUtils.isNotBlank(lock)){
            //获取超时订单
            List<UserOrderRecord> overtimeOrders = userOrderRecordService.getOvertimeOrders();
            if (CollectionUtil.isNotEmpty(overtimeOrders)){
                for (UserOrderRecord record : overtimeOrders) {
                    //完成订单
                    userOrderRecordService.completeOrder(record.getUserId(),record.getId());
                    OrderEvaluateDTO dto = new OrderEvaluateDTO();
                    dto.setOrderId(record.getId());
                    dto.setContent("系统默认好评");
                    dto.setIsAnonymous(Boolean.FALSE);
                    dto.setIsSatisfied(Boolean.TRUE);
                    userOrderRecordService.evaluate(record.getUserId(),dto);
                }
            }
        }
        log.info("订单自动完成结束");
    }
}
